import { defineStore } from "pinia"
import { store } from '@/store'
import { loginApi, logoutApi } from '@/api/user'
import { router } from '@/router'
import { PageEnum } from '@/enums/pageEnum'

export const useUserStore = defineStore("app-user", {
  state: () => {
    return {
      userInfo: {} as any,
      token: null
    }
  },
  getters: {
    getUserInfo(): any {
      return this.userInfo || {}
    },
    getToken(): string {
      return this.token || ''
    }
  },
  actions: {
    setUserInfo(info: any) {
      this.userInfo = info
    },
    setToken(info: any) {
      this.token = info ? info : ''; // for null or undefined value
    },
    resetState() {
      this.userInfo = {};
      this.token = null;
    },
    async login(params: Recordable) {
      try {
        const token = await loginApi({
          ...params,
        })
        this.setToken(token)
        return this.afterLoginAction()
      } catch (error) {
        return Promise.reject(error)
      }
    },
    async afterLoginAction() {
      if (!this.getToken) {
        return null
      }
      const userInfo = await this.getUserInfoAction()
      this.setUserInfo(userInfo)
      return userInfo
    },
    async getUserInfoAction() {
      if (!this.getToken) {
        return null
      }
      const userInfo = {}
      return userInfo
    },
    async logout(goLogin = false) {
      if (this.getToken) {
        try {
          await logoutApi({
            userId: this.getUserInfo.id
          });
        } catch {
          console.log('注销Token失败');
        }
      }
      this.setToken(null);
      goLogin && router.push(PageEnum.BASE_LOGIN)
    }
  },
  persist: true
})

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store);
}